﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Web.Core;
using System.Collections;
using System.Collections.Specialized;

namespace Yuanlin.Business
{
    public class CompanyProductEditControl : YuanlinUserControl,
        IReplyConverter<CompanyProductReply, GetOperation>
    {
        protected ValuedTextBox titleValuedTextBox;//名称
        protected ValuedTextBox aliasValuedTextBox;//别名
        protected ValuedTextBox pinNameTitleValuedTextBox;//品种
        protected RadioButtonList categoryRadioButtonList;//植物分类
        protected CheckBoxList applicationCategoryCheckBoxList;
        protected ValuedTextBox numberValuedTextBox;//数量
        protected ValuedTextBox priceValuedTextBox;//价格
        protected CheckBoxList zhongzhiMethodCheckBoxList;//种植方式
        protected CheckBoxList seedlingattributeCheckBoxList;//苗木属性
        protected ValuedTextBox registerTrademarkValuedTextBox;//注册商标
        protected ValuedCheckBox productPriceFromFaceCheckBox;//是否面议
        protected RadioButtonList expiredInfoRadioButtonList;//信息有效期
        protected ValuedEditor descriptionValuedEditor;
        protected ValuedTextBox miJingValuedTextBox;//米经
        protected ValuedTextBox diJingValuedTextBox;//地径
        protected HiddenField specificationHiddenField;
        protected HiddenField applicationSpecificationHiddenField;
        protected Literal editProductLiteral;
        protected Label avgPriceLtl;
        protected HtmlInputFile attachmentData;
        protected IButton SaveButton;
        protected IButton BackButton;
        private CompanyProduct product = null;
        private string tradeType = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.TradeType);
        private YuanlinUser user = HttpContext.Current.User as YuanlinUser;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            requestBinders.Add(RequestHelper.BuildGetCompanyProductRequest(this));
        }
        protected override void OnLoad(EventArgs e)
        {
            SaveButton.Click += new EventHandler(SaveButton_Click);
            BackButton.Click += new EventHandler(BackButton_Click);
            AjaxManager.Register(this, "AjaxMethod");
        }

        private void Bind()
        {
            //植物分类
            ProductCategoryListRequest request = new ProductCategoryListRequest();
            request.CategoryType = 0;
            EntityList categories = BusinessManager.GetProductCategoryList(RequestHelper.BuildGetProductCategoryListRequest(request));
            this.categoryRadioButtonList.DataSource = categories;
            this.categoryRadioButtonList.DataTextField = "Title";
            this.categoryRadioButtonList.DataValueField = "EntityId";
            this.categoryRadioButtonList.DataBind();

            //应用分类
            ProductCategoryListRequest request1 = new ProductCategoryListRequest();
            request1.CategoryType = 1;
            EntityList applicationCategories = BusinessManager.GetProductCategoryList(RequestHelper.BuildGetProductCategoryListRequest(request1));
            applicationCategoryCheckBoxList.DataSource = applicationCategories;
            applicationCategoryCheckBoxList.DataValueField = "EntityId";
            applicationCategoryCheckBoxList.DataTextField = "Title";
            applicationCategoryCheckBoxList.DataBind();

            //种植方式
            EntityList zhongzhiMethods = BusinessManager.GetZhongzhiMethodList(RequestHelper.BuildGetZhongzhiMethodListRequest());
            zhongzhiMethodCheckBoxList.DataSource = zhongzhiMethods;
            zhongzhiMethodCheckBoxList.DataValueField = "EntityId";
            zhongzhiMethodCheckBoxList.DataTextField = "Title";
            zhongzhiMethodCheckBoxList.DataBind();

            //苗木属性
            EntityList seedlingattributes = BusinessManager.GetSeedlingAttributeList(RequestHelper.BuildGetSeedlingAttributeListRequest());
            seedlingattributeCheckBoxList.DataSource = seedlingattributes;
            seedlingattributeCheckBoxList.DataValueField = "EntityId";
            seedlingattributeCheckBoxList.DataTextField = "Title";
            seedlingattributeCheckBoxList.DataBind();

            //信息有效期
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("5天", "1"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("15天", "2"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("一个月", "3"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("三个月", "4"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("六个月", "5"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("九个月", "6"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("十二个月", "7"));

            switch (tradeType)
            {
                case "0":
                    {
                        editProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_EditCompanyProduct", "ControlPanelResources.xml");
                    }
                    break;
                case "2":
                    {
                        editProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_EditCompanyProductQiuGou", "ControlPanelResources.xml");
                    }
                    break;
                case "1":
                    {
                        editProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_EditCompanyProductJingPin", "ControlPanelResources.xml");
                    }
                    break;
                case "3":
                    {
                        editProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_EditCompanyProductJiShou", "ControlPanelResources.xml");
                    }
                    break;
            }

            if (product != null)
            {
                this.titleValuedTextBox.Value = product.Title.Value;
                ProductListRequest productListRequest = new ProductListRequest();
                productListRequest.EqualTitle = product.Title.Value;
                EntityList products = BusinessManager.GetProductList(RequestHelper.BuildGetProductListRequest(productListRequest));
                if (products.Count > 0)
                {
                    aliasValuedTextBox.Value = (products[0] as Product).Alias.Value;
                }
                pinNameTitleValuedTextBox.Value = product.PinNameTitle.Value;
                categoryRadioButtonList.SelectedValue = product.CategoryId.Value.ToString();
                ListItem item = null;
                numberValuedTextBox.Value = product.Number.Value.ToString();
                priceValuedTextBox.Value = product.Price.Value.ToString("f2");
                miJingValuedTextBox.Value = product.MiJing.Value.ToString("f2");
                diJingValuedTextBox.Value = product.DiJing.Value.ToString("f2");
                foreach (string itemstrm in product.ZhongzhiMethod.Value.Split(','))
                {
                    item = this.zhongzhiMethodCheckBoxList.Items.FindByValue(itemstrm);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
                foreach (string itemstrm in product.SeedlingAttribute.Value.Split(','))
                {
                    item = this.seedlingattributeCheckBoxList.Items.FindByValue(itemstrm);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
                registerTrademarkValuedTextBox.Value = product.RegisterTrademark.Value;
                this.productPriceFromFaceCheckBox.Value = product.ProductPriceFromFace.Value.ToString();
                expiredInfoRadioButtonList.SelectedValue = product.ExpiredInfo.Value.ToString();
                this.descriptionValuedEditor.Value = product.Body.Value;
                avgPriceLtl.Text = product.AvgPrice.Value.ToString();
                if (product.CategoryId.Value > -1)
                {
                    BindSpecification();
                }

                HuamuAndCategoryRelationListRequest request2 = new HuamuAndCategoryRelationListRequest();
                request2.HuamuId = product.EntityId.Value;
                EntityList huamuAndCategoryRelationList = BusinessManager.GetHuamuAndCategoryRelationList(RequestHelper.BuildGetHuamuAndCategoryRelationListRequest(request2));
                if (huamuAndCategoryRelationList.Count == 0)
                    return;

                foreach (HuamuAndCategoryRelation huamuAndCategoryRelation in huamuAndCategoryRelationList)
                {
                    item = this.applicationCategoryCheckBoxList.Items.FindByValue(huamuAndCategoryRelation.CategoryId.Value.ToString());
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
            }
        }

        private void BindSpecification()
        {
            string returnValue = string.Empty;
            if (string.IsNullOrEmpty(product.GuiGeNames.Value) || string.IsNullOrEmpty(product.GuiGeValues.Value))
            {
                return;
            }
            string[] names = product.GuiGeNames.Value.Split(new string[] { "|" }, StringSplitOptions.None);
            string[] values = product.GuiGeValues.Value.Split(new string[] { "|" }, StringSplitOptions.None);
            string[] units = product.GuiGeUnits.Value.Split(new string[] { "|" }, StringSplitOptions.None);

            if (names.Length != values.Length)
            {
                return;
            }
            for (int i = 0; i < names.Length; i++)
            {
                returnValue += ";" + string.Format("{0}:{1}:{2}", names[i], units[i], values[i]);
            }
            if (returnValue.Length > 0)
            {
                returnValue = returnValue.Substring(1);
            }
            //绑定规格
            specificationHiddenField.Value = returnValue;

        }
       
        private void SetProductId(CompanyProduct companyProduct)
        {
            ProductListRequest request = new ProductListRequest();
            request.Title = companyProduct.Title.Value;
            EntityList products = BusinessManager.GetProductList(RequestHelper.BuildGetProductListRequest(request));
            if (products.TotalCount > 0)
            {
                companyProduct.ProductId.Value = products[0].EntityId.Value;
            }
            else
            {
                companyProduct.ProductId.Value = 0;
            }
        }

        public void BackButton_Click(object sender, EventArgs e)
        {
            if (tradeType == "0")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyProductListUrl());
            }
            else if (tradeType == "2")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyProductQiuGouListUrl());
            }
            else if (tradeType == "1")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyProductJingPinListUrl());
            }
            else if (tradeType == "3")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyProductJiShouListUrl());
            }
        }

        public void SaveButton_Click(object sender, EventArgs e)
        {
            

            product.Title.Value =  CensorWordManager.CensorWord(titleValuedTextBox.Value);
            product.PinNameTitle.Value =  CensorWordManager.CensorWord(pinNameTitleValuedTextBox.Value);
            product.CategoryId.Value = Int32.Parse(categoryRadioButtonList.SelectedValue);
            product.Number.Value = this.numberValuedTextBox.Value.Length == 0 ? 0 : Convert.ToInt32(this.numberValuedTextBox.Value);
            product.Price.Value = priceValuedTextBox.Value.Length == 0 ? 0 : (float)(Convert.ToDecimal(priceValuedTextBox.Text));
            product.MiJing.Value = miJingValuedTextBox.Value.Length == 0 ? 0 : (float)(Convert.ToDecimal(miJingValuedTextBox.Text));
            product.DiJing.Value = diJingValuedTextBox.Value.Length == 0 ? 0 : (float)(Convert.ToDecimal(diJingValuedTextBox.Text));
            product.ZhongzhiMethod.Value = "";
            foreach (ListItem item in this.zhongzhiMethodCheckBoxList.Items)
            {
                if (item.Selected)
                {
                    product.ZhongzhiMethod.Value += "," + item.Value;
                }
            }
            if (product.ZhongzhiMethod.Value.Length > 0)
            {
                product.ZhongzhiMethod.Value = product.ZhongzhiMethod.Value.Substring(1);
            }
            foreach (ListItem item in this.seedlingattributeCheckBoxList.Items)
            {
                if (item.Selected)
                {
                    product.SeedlingAttribute.Value += "," + item.Value;
                }
            }
            if (product.SeedlingAttribute.Value.Length > 0)
            {
                product.SeedlingAttribute.Value = product.SeedlingAttribute.Value.Substring(1);
            }
            product.RegisterTrademark.Value =  CensorWordManager.CensorWord(registerTrademarkValuedTextBox.Value);
            product.ProductPriceFromFace.Value = this.productPriceFromFaceCheckBox.Value.ToLower() == "false" ? 0 : 1;
            product.ExpiredInfo.Value = Int32.Parse(expiredInfoRadioButtonList.SelectedValue);
            product.Body.Value =  CensorWordManager.CensorWord(this.descriptionValuedEditor.Value);
            product.UpdateDate.Value = DateTime.Now;

            product.GreenNum.Value = user.CurrentGreenNumber;

            List<string> fieldNames = new List<string>();
            List<string> fieldValues = new List<string>();
            List<string> fieldUnits = new List<string>();
            if (specificationHiddenField.Value.Length > 0)
            {
                string[] specifications = specificationHiddenField.Value.Split(';');
                foreach (string item in specifications)
                {
                    fieldNames.Add(item.Split(':')[0]);
                    fieldValues.Add(item.Split(':')[1]);
                    fieldUnits.Add(item.Split(':')[2]);
                }
            }
            product.GuiGeNames.Value = string.Join("|", fieldNames.ToArray());
            product.GuiGeValues.Value = string.Join("|", fieldValues.ToArray());
            product.GuiGeUnits.Value = string.Join("|", fieldUnits.ToArray());

            SetProductId(product);

            BusinessManager.UpdateCompanyProduct(product);

            //创建花木与应用分类的关系
            HuamuAndCategoryRelation huamuAndCategoryRelation = new HuamuAndCategoryRelation();
            huamuAndCategoryRelation.EntityId.Value = 1;
            huamuAndCategoryRelation.HuamuId.Value = product.EntityId.Value;
            foreach (ListItem item in this.applicationCategoryCheckBoxList.Items)
            {
                if (item.Selected)
                {
                    huamuAndCategoryRelation.CategoryIds += "," + Globals.ChangeType<int>(item.Value);
                }
            }
            if (!string.IsNullOrEmpty(huamuAndCategoryRelation.CategoryIds))
            {
                huamuAndCategoryRelation.CategoryIds = huamuAndCategoryRelation.CategoryIds.Substring(1);
                BusinessManager.UpdateHuamuAndCategoryRelation(huamuAndCategoryRelation);
            }
            if (SiteUrls.Instance().IsAttachmentValid(attachmentData))
            {
                product.AttachmentFileName.Value = SiteUrls.Instance().GetPostedFileName(attachmentData);
                BusinessManager.UpdateCompanyProduct(product);
                SiteUrls.Instance().SaveFile(SiteUrls.Instance().GetFile(product), attachmentData);
            }
            BackButton_Click(null, null);

        }

        #region Ajax Method

        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string ParentCategorySelectedChanged(string selectedValue)
        {
            if (string.IsNullOrEmpty(selectedValue))
            {
                return "";
            }

            return BindProductsAndSpecifications(int.Parse(selectedValue));
        }
        private string BindProductsAndSpecifications(int categoryID)
        {
            string returnValue = string.Empty;
            if (categoryID < 0)
            {
                return returnValue;
            }

            //绑定规格
            ProductSpecificationListRequest request = new ProductSpecificationListRequest();
            request.ProductCategoryId = categoryID;
            EntityList productSpecifications = BusinessManager.GetProductSpecificationList(RequestHelper.BuildGetProductSpecificationListRequest(request));
            if (productSpecifications.Count > 0)
            {
                string specificationFormat = "{0}:{1}";
                string specificationString = string.Empty;
                foreach (ProductSpecification specification in productSpecifications)
                {
                    if (specificationString != string.Empty)
                    {
                        specificationString += ";";
                    }
                    specificationString += string.Format(specificationFormat, specification.Title, specification.Unit);
                }
                returnValue = specificationString;
            }

            return returnValue;
        }

        #endregion

        #region IReplyConverter<CompanyProductReply,GetOperation> Members

        public void ConvertReply(CompanyProductReply reply, GetOperation operation)
        {
            if (reply != null)
            {
                product = reply.Entity as CompanyProduct;

                if (!Page.IsPostBack)
                {
                    Bind();
                }
            }
        }

        #endregion
    }
}